﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RH.Domain;
using RH.Web.ViewModels;
using AutoMapper;
using RH.Web.Utility;

namespace RH.Web.Controllers
{
    [Authorize]
    public class UserController : BaseController
    {
        private AppEntities _Context = new AppEntities();

        public UserController()
        {            
        }

        public UserController(UserViewModel currentUser)
            : base(currentUser)
        {
        }

        public ActionResult Index()
        {            
            return View();
        }
        /// <summary>
        /// Gets an User from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id = 0)
        {
            User user = id == 0 ? new User() : _Context.Users.FirstOrDefault(P => P.ID == id);            
            UserViewModel userModel = Mapper.Map<User, UserViewModel>(user); 
            //ViewBag.UserToEdit = user;
            return View(userModel);
        }
        /// <summary>
        /// Saves User Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(UserViewModel viewModel)
        {
            if (!ModelState.IsValid)
                return View(viewModel);

            User user = null;
            if (viewModel.ID == 0)
            {
                user = new User();
                _Context.AddToUsers(user);
            }
            else
                _Context.Users.FirstOrDefault(P => P.ID == viewModel.ID);

            user = Mapper.Map<UserViewModel, User>(viewModel, user);
            _Context.SaveChanges();
            return RedirectToAction("Edit", "UserController");
        } 
    }
}
